package com.itheima.app.manager;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.itheima.app.interceptor.UserThreadLocal;
import com.itheima.domain.db.TanHua;
import com.itheima.domain.db.UserInfo;
import com.itheima.domain.mongo.*;
import com.itheima.service.db.SoulService;
import com.itheima.service.db.UserInfoService;
import com.itheima.vo.*;
import org.apache.dubbo.config.annotation.DubboReference;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.*;
import java.util.stream.Collectors;

@Service
public class SoulManager {

    @DubboReference(version = "1.0.0")
    private SoulService soulService;
    @DubboReference
    UserInfoService userInfoService;

    //测灵魂   问卷列表
    public  List<SoulVo> soulQustionsList() {
        TanHua tanHua = UserThreadLocal.get();
        List<Soul> soulList = soulService.querySoulList(tanHua.getId());
        List<SoulVo> soulVoList = new ArrayList<>();

        if (CollectionUtils.isEmpty(soulList)) {
            //为用户生成3套题目
            for (int i = 1; i <= 3; i++) {
                List<Question> questions = soulService.queryQuestions(i);
                Collections.shuffle(questions);
                questions = questions.stream().limit(10).collect(Collectors.toList());
                Soul soul = this.creatSoul(questions, 1);
                //保存
                soulService.saveSoul(soul);
                soulList.add(soul);
            }
        }

        for (Soul soul : soulList) {
            SoulVo soulVo = new SoulVo();

            soulVo.setId(String.valueOf(soul.getId()));
            soulVo.setCover(soul.getCover());
            soulVo.setIsLock(soul.getIsLock());
            soulVo.setName(soul.getName());
            soulVo.setLevel(soul.getLevel());
            soulVo.setStar(soul.getStar());

            soulVo.setReportId(soulService.queryReportId(soulVo.getId()));

            List<Question> questionList = soulService.queryQuestionList(soul.getQuestionIds());
            ArrayList<SoulQuestionsVo> vo = new ArrayList<>();

            for (Question option : questionList) {
                SoulQuestionsVo qvo = new SoulQuestionsVo();
                qvo.setId(String.valueOf(option.getId()));
                qvo.setQuestion(option.getQuestion());

                List<Option> options = option.getOptions();
                ArrayList<SoulOptionsVo> vos = new ArrayList<>();
                for (Option op : options) {
                    SoulOptionsVo v = new SoulOptionsVo();
                    v.setId(op.getId().toString());
                    v.setOption(op.getOption());

                    vos.add(v);
                }

                qvo.setOptions(vos);
                vo.add(qvo);
            }
            soulVo.setQuestions(vo);
            soulVoList.add(soulVo);
        }


        return soulVoList;
    }

    private Soul creatSoul(List<Question> questions, int i) {
        TanHua tanHua = UserThreadLocal.get();
        Soul soul = new Soul();

        List<ObjectId> questionIds = new ArrayList<>();

        for (Question question : questions) {
            questionIds.add(question.getId());
        }
        soul.setId(new ObjectId());
        soul.setQuestionIds(questionIds);
        soul.setUserId(tanHua.getId());
        if (1 == i) {
            soul.setCover("https://tanhua-dev.oss-cn-zhangjiakou.aliyuncs.com/images/test_soul/qn_cover_01.png");
            soul.setIsLock(0);
            soul.setLevel("初级");
            soul.setName("初级灵魂题");
            soul.setStar(2);
        } else if (2 == i) {
            soul.setCover("https://tanhua-dev.oss-cn-zhangjiakou.aliyuncs.com/images/test_soul/qn_cover_02.png");
            soul.setIsLock(1);
            soul.setLevel("中级");
            soul.setName("中级灵魂题");
            soul.setStar(3);
        } else if (3 == i) {
            soul.setCover("https://tanhua-dev.oss-cn-zhangjiakou.aliyuncs.com/images/test_soul/qn_cover_03.png");
            soul.setIsLock(1);
            soul.setLevel("高级级");
            soul.setName("高级灵魂题");
            soul.setStar(5);
        }
        return soul;
    }


    public String SaveSoulAnswer(Map<String, List<Answer>> answer) {
        List<Answer> answers = answer.get("answers");
        int score = 0;

        //查询所有的题目  项目
        Question question = null;
        for (Answer answer1 : answers) {
            question = soulService.queryQuestion(answer1.getQuestionId());
            List<Option> options = question.getOptions();

            for (Option option : options) {
                if (answer1.getOptionId().equals(String.valueOf(option.getId()))) {
                    score += option.getScore();
                    break;
                }
            }

        }
        Integer type = question.getType();
        String level = "";
        if (1 == type) {
            level = "初级";
        } else if (2 == type) {
            level = "中级";
        } else {
            level = "高级";
        }
        Report report = this.result(score, level);

        return soulService.saveReport(report);
    }

    private Report result(int score, String level) {
        TanHua tanHua = UserThreadLocal.get();

        String soulId = soulService.querySoulId(level, tanHua.getId());

        Report report = new Report();
        report.setSoulId(new ObjectId(soulId));

        List<DimensionVo> list = new ArrayList<>();

        if (score <= 20) {
            report.setConclusion("猫头鹰：他们的共同特质为重计划、条理、细节精准。在行为上，表现出喜欢理性思考与分析、较重视制度、结构、规范。他们注重执行游戏规则、循规蹈矩、巨细靡遗、重视品质、敬业负责。");
            report.setCover("https://tanhua-dev.oss-cn-zhangjiakou.aliyuncs.com/images/test_soul/owl.png");
            report.setUserId(tanHua.getId());

            list.add(new DimensionVo("内向", "75%"));
            list.add(new DimensionVo("判断", "80%"));
            list.add(new DimensionVo("可靠", "60%"));
            list.add(new DimensionVo("理性", "75%"));

            report.setDimensions(list);
        } else if (20 < score && score <= 40) {
            report.setConclusion("白兔型：平易近人、敦厚可靠、避免冲突与不具批判性。在行为上，表现出不慌不忙、冷静自持的态度。他们注重稳定与中长程规划，现实生活中，常会反思自省并以和谐为中心，即使面对困境，亦能泰然自若，从容应付。");
            report.setCover("https://tanhua-dev.oss-cn-zhangjiakou.aliyuncs.com/images/test_soul/rabbit.png");
            report.setUserId(tanHua.getId());

            list.add(new DimensionVo("稳定", "70%"));
            list.add(new DimensionVo("友善", "75%"));
            list.add(new DimensionVo("耐心", "80%"));
            list.add(new DimensionVo("可靠", "80%"));
            report.setDimensions(list);
        }else if (41< score && score <= 55) {
            report.setConclusion("狐狸型 ：人际关系能力极强，擅长以口语表达感受而引起共鸣，很会激励并带动气氛。他们喜欢跟别人互动，重视群体的归属感，基本上是比较「人际导向」。由于他们富同理心并乐于分享，具有很好的亲和力，在服务业、销售业、传播业及公共关系等领域中，狐狸型的领导者都有很杰出的表现。");
            report.setCover("https://tanhua-dev.oss-cn-zhangjiakou.aliyuncs.com/images/test_soul/fox.png");
            report.setUserId(tanHua.getId());

            list.add(new DimensionVo("外向", "70%"));
            list.add(new DimensionVo("自信", "75%"));
            list.add(new DimensionVo("乐观", "80%"));
            list.add(new DimensionVo("热情", "60%"));
            report.setDimensions(list);
        }else if (56<=score){
            report.setConclusion("狮子型：性格为充满自信、竞争心强、主动且企图心强烈，是个有决断力的领导者。一般而言，狮子型的人胸怀大志，勇于冒险，看问题能够直指核心，并对目标全力以赴。\\\\n\\\" +\\n\" +\n" +
                    "        \"                    \\\"他们在领导风格及决策上，强调权威与果断，擅长危机处理，此种性格最适合开创性与改革性的工作。");
            report.setCover("https://tanhua-dev.oss-cn-zhangjiakou.aliyuncs.com/images/test_soul/lion.png");
            report.setUserId(tanHua.getId());

            list.add(new DimensionVo("外向", "80%"));
            list.add(new DimensionVo("自信", "85%"));
            list.add(new DimensionVo("果断", "80%"));
            list.add(new DimensionVo("强势", "90%"));
            report.setDimensions(list);
        }
        return report;
    }

    public ReportVo queryReport(String reportId) {
        ReportVo reportVo=new ReportVo();
        Report report = soulService.queryReport(reportId);
        if (null==report){
            return reportVo;
        }
        reportVo.setConclusion(report.getConclusion());
        reportVo.setCover(report.getCover());
        reportVo.setDimensions(report.getDimensions());

        //查询与你类似的人
        List<Report> reportList = soulService.querySimilarYou(report);
        if (CollectionUtils.isEmpty(reportList)){
            reportVo.setSimilarYou(null);
        }

        Set<Long> userIds=new HashSet<>();

        for (Report rp : reportList) {
            if (report.getUserId().equals(rp.getUserId())){
                continue;
            }
            userIds.add(rp.getUserId());
        }

        //截取  最多10用户进行推荐
        int recommendCount = Math.min(10, userIds.size());
        userIds=userIds.stream().limit(recommendCount).collect(Collectors.toSet());

        List<UserInfo> userInfos=new ArrayList<>();
        if (CollectionUtils.isEmpty(userIds)){
            QueryWrapper<UserInfo> queryWrapper=new QueryWrapper<>();
            queryWrapper.in("user_id",userIds);
            userInfos=userInfoService.save(queryWrapper);
        }

        List<SimilarYouVo> similarList=new ArrayList<>();

        for (UserInfo userInfo : userInfos) {
            SimilarYouVo similarYou=new SimilarYouVo();

            similarYou.setId(userInfo.getId());
            similarYou.setAvatar(userInfo.getAvatar());

            similarList.add(similarYou);
        }
        reportVo.setSimilarYou(similarList);
        return reportVo;
    }
}
